<?php

class diquModule extends Model
{
    public function __construct()
    {
        parent::__construct("diqu");
    }

    /**
     * 获取树状图
     * @date: 2019年7月8日 下午3:51:07
     * @param: variable
     * @return:
     * @author: 龚华尧
     */
    public function gettreelistByclassid($classid = "")
    {
        //报告所有错误
        error_reporting(E_ALL);
        $whereStr = "";
        if ($classid != "") {
            $whereStr = "class_id={$classid} ";
        }
        $list = $this->find("id,biaoti as name,class_id as classid,paixu")->where($whereStr)->orderBy("paixu asc,id desc")->all();
        $list = $this->child($list);
        //var_dump($list);
        return $list;
    }

    //对给定的数组进行重新排序
    public function tree($arr, $pid = 0, $level = 0)
    {
        static $res = array();
        foreach ($arr as $v) {
            if ($v['classid'] == $pid) {
                //说明找到，先保存
                $v['level'] = $level;
                $res[] = $v;
                //改变条件，递归查找
                $this->tree($arr, $v['id'], $level + 1);
            }
        }
        return $res;
    }

    //将平行的二维数组，转成包含关系的多维数组
    public function child($arr, $pid = 0)
    {
        $res = array();
        foreach ($arr as $v) {
            if ($v['classid'] == $pid) {
                //找到了，继续查找其后代节点
                //$temp = $this->child($arr,$v['cat_id']);
                //将找到的结果作为当前数组的一个元素来保存，其下标是child
                //$v['child'] = $temp;
                $v['child'] = $this->child($arr, $v['id']);
                $res[] = $v;
                unset($v);
            }

        }
        return $res;
    }

}